// ignore_for_file: library_private_types_in_public_api, use_build_context_synchronously
import 'dart:io';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:intl/intl.dart';
import 'package:number_paginator/number_paginator.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sp_util/sp_util.dart';
import 'package:syncfusion_flutter_datagrid_export/export.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart' as xlsio;
import 'package:flutter/material.dart';
import 'package:storage/database.dart';
import 'package:storage/model/warehouse_in_out_model_entity.dart';
import 'package:storage/source/warehouse_in_source.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class WarehouseInPage extends StatefulWidget {
  const WarehouseInPage({super.key});

  @override
  _WarehouseInPageState createState() => _WarehouseInPageState();
}

class _WarehouseInPageState extends State<WarehouseInPage> {
  List<WarehouseInOutModelEntity> modelList = [];
  late WarehouseInSource warehouseOutSource;

  final TextEditingController _companyController = TextEditingController();
  final TextEditingController _goodsController = TextEditingController();

  @override
  void dispose() {
    _companyController.dispose();
    _goodsController.dispose();
    _controller.dispose();
    super.dispose();
  }

  bool needPage = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      needPage = SpUtil.getBool('needPage') ?? false;

      refreshData();
    });
  }

  int pageNum = 1;
  int pageSize = 20;
  int total = 0;
  String? warehouseTime;

  Future<void> refreshData() async {
    modelList.clear();
    CommonListModel result = await DatabaseHelper().getWarehouseRecordList(0,
        goodName: _goodsController.text,
        companyName: _companyController.text,
        pageNum: needPage ? pageNum : null,
        pageSize: needPage ? pageSize : null,
        warehouseTime: warehouseTime);

    total = (result.total / pageSize).ceil();

    modelList = result.data.reversed
        .map((e) => WarehouseInOutModelEntity.fromJson(e))
        .toList();
    warehouseOutSource = WarehouseInSource(warehouseInData: modelList);

    setState(() {});
  }

  final NumberPaginatorController _controller = NumberPaginatorController();

  Widget _buildBottomNumberPagination() {
    return NumberPaginator(
      config: const NumberPaginatorUIConfig(
          mainAxisAlignment: MainAxisAlignment.center),
      controller: _controller,
      // by default, the paginator shows numbers as center content
      numberPages: total,
      onPageChange: (int index) {
        pageNum = index + 1;
        refreshData();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('入库记录列表'),
      ),
      body: Container(
        color: Colors.white,
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Column(
                children: [
                  Row(
                    children: [
                      SizedBox(
                        width: 200,
                        height: 40,
                        child: TextField(
                          controller: _goodsController,
                          maxLines: 1,
                          onSubmitted: (value) {
                            refreshData();
                          },
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderSide: const BorderSide(
                                    width: 2.0, color: Colors.black),
                                // 边框样式
                                borderRadius:
                                    BorderRadius.circular(10.0), // 设置圆角半径
                              ),
                              hintText: '请输入商品名称搜索',
                              hintStyle: const TextStyle(color: Colors.grey)),
                        ),
                      ),
                      const SizedBox(width: 10),
                      // 选择时间段按钮
                      GestureDetector(
                        onTap: () async {
                          DateTime? pickedDate = await showDatePicker(
                            context: context,
                            firstDate: DateTime(2000),
                            lastDate: DateTime(2100),
                            currentDate: DateTime.now(),
                          );

                          if (pickedDate != null) {
                            setState(() {
                              warehouseTime =
                                  DateFormat('yyyy-MM-dd').format(pickedDate);
                            });
                          }
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 8),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.black, width: 2),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Row(
                            children: [
                              const Icon(Icons.date_range, color: Colors.black),
                              const SizedBox(width: 5),
                              Text(
                                warehouseTime != null
                                    ? warehouseTime!
                                    : "选择入库时间",
                                style: const TextStyle(color: Colors.black),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            /// 搜索
                            refreshData();
                          },
                          child: const Text('搜索')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            _goodsController.clear();
                            _companyController.clear();
                            warehouseTime = null;
                            refreshData();
                          },
                          child: const Text('重置')),
                      const SizedBox(width: 10),
                      FilledButton(
                          onPressed: () {
                            exportDataGridToExcel();
                          },
                          child: const Text('导出excel')),
                    ],
                  ),
                  const SizedBox(height: 20),
                  if (modelList.isNotEmpty)
                    Expanded(
                      child: SfDataGrid(
                        key: _key,
                        rowHeight: 40,
                        headerRowHeight: 40,
                        source: warehouseOutSource,
                        columnWidthMode: ColumnWidthMode.fill,
                        showCheckboxColumn: true,
                        selectionMode: SelectionMode.multiple,
                        //开启列宽度调节
                        allowColumnsResizing: true,
                        onSelectionChanged: onSelectionChanged,
                        columns: <GridColumn>[
                          GridColumn(
                              columnName: 'id',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  alignment: Alignment.center,
                                  child: const Text(
                                    'id',
                                    style: TextStyle(color: Colors.white),
                                  ))),
                          GridColumn(
                              columnName: '商品名称',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  alignment: Alignment.center,
                                  child: const Text(
                                    '商品名称',
                                    style: TextStyle(color: Colors.white),
                                  ))),  GridColumn(
                              columnName: '商品规格',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  alignment: Alignment.center,
                                  child: const Text(
                                    '商品规格',
                                    style: TextStyle(color: Colors.white),
                                  ))),
                          GridColumn(
                              columnName: '商品成本价',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  alignment: Alignment.center,
                                  child: const Text(
                                    '商品成本价',
                                    style: TextStyle(color: Colors.white),
                                  ))),
                          GridColumn(
                              columnName: '入库数量',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  alignment: Alignment.center,
                                  child: const Text(
                                    '入库数量',
                                    style: TextStyle(color: Colors.white),
                                  ))),
                          GridColumn(
                              columnName: '入库时间',
                              label: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: const BoxDecoration(
                                      color: Colors.lightBlueAccent,
                                      border: Border(
                                        right: BorderSide(
                                            color: Colors.grey, width: 1),
                                        left: BorderSide(
                                            color: Colors.grey, width: 1),
                                      )),
                                  alignment: Alignment.center,
                                  child: const Text(
                                    '入库时间',
                                    style: TextStyle(color: Colors.white),
                                  ))),
                        ],
                      ),
                    ),
                ],
              ),
            ),
            if (needPage&& total > 0) _buildBottomNumberPagination()
          ],
        ),
      ),
    );
  }

  final GlobalKey<SfDataGridState> _key = GlobalKey<SfDataGridState>();

  /// 导出excel
  Future<void> exportDataGridToExcel() async {
    // 获取当前应用的文档目录
    Directory documentsDirectory = await getApplicationDocumentsDirectory();

    // 创建一个名为“excel汇总”的子文件夹，如果不存在则创建
    Directory excelSummaryDirectory =
        Directory('${documentsDirectory.path}/excel汇总');
    if (!await excelSummaryDirectory.exists()) {
      await excelSummaryDirectory.create();
    }

    // 导出 SfDataGrid 数据到 Excel
    final xlsio.Workbook workbook = _key.currentState!.exportToExcelWorkbook(
      excludeColumns: ['id'],
    );
    final List<int> bytes = workbook.saveAsStream();
    workbook.dispose();

    // 生成唯一的文件名，避免覆盖同名文件
    String fileName = '入库表_${DateTime.now().millisecondsSinceEpoch}.xlsx';
    File file = File('${excelSummaryDirectory.path}/$fileName');

    // 将文件写入到指定路径
    await file.writeAsBytes(bytes);

    showToast('入库表导出成功', context: context);
  }

  List<int> selectedIdList = [];

  // 表格选择事件改变回调
  void onSelectionChanged(
      List<DataGridRow> addedRows, List<DataGridRow> removedRows) {
    if (addedRows.isEmpty && removedRows.isEmpty) {
      for (DataGridRow row in warehouseOutSource.rows) {
        int id = row.getCells().first.value as int;
        selectedIdList.remove(id);
      }
    }
    for (DataGridRow addedRow in addedRows) {
      int id = addedRow.getCells().first.value as int;
      if (!selectedIdList.contains(id)) {
        selectedIdList.add(id);
      }
    }
    for (DataGridRow removedRow in removedRows) {
      int id = removedRow.getCells().first.value as int;
      selectedIdList.remove(id);
    }
    setState(() {});
  }
}
